import baseURL from "./config.js"
/**
 * 拼接对象为请求字符串
 * 对于需要编码的文本（比如说中文）我们要进行编码
 * @param {Object} obj - 待拼接的对象
 * @returns {string} - 拼接成的请求字符串
 **/
export function formatGetUri(obj) {
	const params = []
	Object.keys(obj).forEach((key) => {
		let value = obj[key]
		if (typeof value !== 'undefined' || value !== null) {
			params.push([key, encodeURIComponent(value)].join('='))
		}
	})
	return '?' + params.join('&')
}

// App显示自动消失的提示消息App
export function showAppToast(message, styles) {
	return function showToast() {
		plus.nativeUI.toast(message, styles);
	}
}

//通用的显示提示消失
export function showToast (title, icon, duration) {
	return uni.showToast({
        title: title || "",
        icon: icon || "success",
        duration: duration || 1500
    })
}

/**
 * 截取取小数点后位数
 */
export function formatDecimal(num, decimal) {
    num = num.toString()
    let index = num.indexOf('.')
    if (index !== -1) {
        num = num.substring(0, decimal + index + 1)
    } else {
        num = num.substring(0)
    }
    return parseFloat(num).toFixed(decimal)
}
/**
 * 上传身份证图片识别
 */
export function uploadCard(url, id) {
    let b = new Promise((resolve, reject) => {
        uni.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                let tempFilePaths = res.tempFilePaths;
                uni.showLoading({
                    title: "上传识别中",
                    mask: true,
                })
                uni.uploadFile({
                    url: baseURL + url + "",
                    method: "POST",
                    filePath: tempFilePaths[0],
                    name: 'file',
                    header: ({
                        "DTG_MARK": uni.getStorageSync('token'),
                    }),
                    success(res) {
                        let data = JSON.parse(res.data)
                        if (data.code == 200) {
                            uni.hideLoading()
                            uni.showToast({
                                title: "上传成功",
                                icon: 'none',
                            })
                            data.filePath = tempFilePaths[0]
                            data.showId = id
                        } else {
                            uni.hideLoading()
                            uni.showToast({
                                title: data.message,
                                icon: 'none',
                            })
                        }
                        resolve(data)
                    },
                    error(err) {
                        reject(err)
                    }
                })
            }
        })
    })
    return b
}
/**
 * 展示图片
 */
export function showImg(e, list) {
    let urlList = []
    list.map(item => {
        urlList.push(item.accessorySaveName)
        return item
    })
	console.log(e);
    uni.previewImage({
        urls: urlList,
		indicator: "default",
        current: e.target.dataset.url ||e.currentTarget.dataset.url
    })
}
/**
 * 上传图片/附件公共接口
 */
export function upload(url, postData){
	let resBody = new Promise((resolve, reject) => {
	    uni.chooseImage({
	        count: 1,
	        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
	        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
	        success: function (res) {
	            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
	            let tempFilePaths = res.tempFilePaths;
	            uni.showLoading({
	                title: "上传中",
	                mask: true,
	            })
	            uni.uploadFile({
	                url: baseURL + url + "",
	                method: "POST",
	                filePath: tempFilePaths[0],
	                name: 'file',
	                header: ({
	                    "DTG_MARK": uni.getStorageSync('token'),
	                }),
					formData: postData,
	                success(res) {
	                    let data = JSON.parse(res.data)
	                    if (data.code == 200) {
	                        uni.hideLoading()
	                        uni.showToast({
	                            title: "上传成功",
	                            icon: 'none',
	                        })
	                    } else {
	                        uni.hideLoading()
	                        uni.showToast({
	                            title: data.message,
	                            icon: 'none',
	                        })
	                    }
	                    resolve(data)
	                },
	                error(err) {
	                    reject(err)
	                }
	            })
	        }
	    })
	})
	return resBody
}

/* 图片加载失败处理 
	that 图片绑定字段所属对象
	dat 图片绑定字段
	name 图片在对象中的字段
*/
export const imgErr = (that, dat, name)=>{
	that[dat][name] = "/static/images/404.png" //默认图片路径
}

/**
 * 一次性上传多少图片
 * list 图片列表
 * formData 上传参数
 */
export const uploadImgsList = (list, formData, url) =>{
	let resBody = new Promise((resolve, reject) =>{
		uni.uploadFile({
			url: baseURL + url,
			files:  list,
			formData: formData,
			header: ({
				"DTG_MARK": uni.getStorageSync('token'),
			}),
			success: (res) => {
				let data = JSON.parse(res.data)
				resolve(data)
			},
			fail: (err) => {  //失败
				let data = JSON.parse(err.data)
				 reject(data)
			},
		})
	})
	return resBody
}

//上传图片
 export async function uploadFileTest(filePath, credentials, suffix) {
	// console.log('---------上传图片')
	return new Promise((resolve) => {
		wx.uploadFile({
			url: credentials.host, //仅为示例，非真实的接口地址
			filePath: filePath,
			name: 'file',
			formData: {
				"policy": credentials.policy,
				"key": credentials.dir + credentials.fileName + '.' + suffix,
				"OSSAccessKeyId": credentials.accessid,
				"Signature": credentials.signature,
				"success_action_status": 200,
				"fileName": credentials.fileName,
			},
			success: () => {
				// console.log('---------上传图片成功')
				resolve(credentials.fileName + '.' + suffix)
			},
			fail: (err) => {
				console.log('---------上传失败', err)
			}
		})
	})

}